package com.xiaoyu.lanling.feature.moment.dialog

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.DialogFragment
import com.xiaoyu.base.app.AppContext
import com.xiaoyu.base.app.GlobalUI
import com.xiaoyu.base.event.AppEventBus
import com.xiaoyu.base.event.SimpleEventHandler
import com.xiaoyu.lanling.R
import com.xiaoyu.lanling.activity.base.BaseDialogFragment
import com.xiaoyu.lanling.event.moment.DeleteMomentEvent
import com.xiaoyu.lanling.feature.moment.data.MomentAction
import kotlinx.android.synthetic.main.moment_action_dialog.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class MomentDeleteDialog : BaseDialogFragment() {

    private val requestTag = Any()

    companion object {
        const val TAG = "MomentDeleteDialog"
        private const val KEY_FID = "key_feed_id"
        private const val KEY_UID = "key_user_id"

        fun newInstance(uid: String, fid: String): MomentDeleteDialog {
            val args = Bundle()
            args.putString(KEY_UID, uid)
            args.putString(KEY_FID, fid)
            val fragment = MomentDeleteDialog()
            fragment.arguments = args
            return fragment
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(DialogFragment.STYLE_NO_TITLE, R.style.DialogFullScreenDimStyle)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.moment_action_dialog, container, false)
    }

    override fun onViewCreatedSafelyAfterAppFinishInit(view: View, savedInstanceState: Bundle?) {
        super.onViewCreatedSafelyAfterAppFinishInit(view, savedInstanceState)
        initView()
        initBind()
        initEvent()
    }

    private fun initView() {
        moment_action_button.text = AppContext.getString(R.string.action_delete)
    }

    private fun initEvent() {
        AppEventBus.bindContainerAndHandler(this, object : SimpleEventHandler() {

            @Subscribe(threadMode = ThreadMode.MAIN)
            fun onEvent(event: DeleteMomentEvent) {

                // NOTE 和删除动态的逻辑不同，这里不可以 dismiss 。删除动态会关闭页面，导致 dialog 的 context 销毁
                // 发生问题
                // dismiss()
                GlobalUI.getInstance().showToast(AppContext.getString(R.string.moment_report_success))
            }
        })
    }

    private fun initBind() {
        moment_action_button.setOnClickListener {
            val uid = arguments?.getString(KEY_UID) ?: return@setOnClickListener
            val fid = arguments?.getString(KEY_FID) ?: return@setOnClickListener
            MomentAction.deleteMoment(requestTag, uid, fid)
            dismiss()
        }
        cancel.setOnClickListener {
            dismiss()
        }
    }
}